<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="用户类型">
                    <el-select
                        class="flex-1"
                        v-model="formData.user_type"
                        clearable
                        placeholder="请选择用户类型"
                        @change="handleUserTypeChange"
                    >
                        <el-option
                            v-for="(item, index) in dictData.user_type"
                            :key="index"
                            :label="item.name"
                            :value="parseInt(item.value)"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="旅行社" v-if="formData.user_type == 2" prop="travel_agency_id">
                    <el-select
                        class="flex-1"
                        v-model="formData.travel_agency_id"
                        clearable
                        placeholder="请选择旅行社"
                    >
                        <el-option
                            v-for="(item, index) in optionsData.trave_agency"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="头像" prop="avatar">
                    <material-picker v-model="formData.avatar" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="real_name">
                    <el-input v-model="formData.real_name" clearable placeholder="请输入真实姓名" />
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                    <el-input v-model="formData.nickname" clearable placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item label="账号" prop="account">
                    <el-input v-model="formData.account" clearable placeholder="请输入账号" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input
                        v-model="formData.password"
                        show-password
                        clearable
                        placeholder="请输入密码"
                    />
                </el-form-item>
                <!-- 确认密码输入框 -->
                <el-form-item label="确认密码" prop="password_confirm">
                    <el-input
                        v-model="formData.password_confirm"
                        show-password
                        clearable
                        placeholder="请输入确认密码"
                    />
                </el-form-item>
                <el-form-item label="用户电话" prop="mobile">
                    <el-input v-model="formData.mobile" clearable placeholder="请输入用户电话" />
                </el-form-item>
                <el-form-item label="用户性别" prop="sex">
                    <el-radio-group v-model="formData.sex" placeholder="请选择用户性别:">
                        <el-radio
                            v-for="(item, index) in dictData.sex"
                            :key="index"
                            :value="parseInt(item.value)"
                        >
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否禁用" prop="is_disable">
                    <el-radio-group v-model="formData.is_disable" placeholder="请选择是否禁用:">
                        <el-radio
                            v-for="(item, index) in dictData.system_disable"
                            :key="index"
                            :value="parseInt(item.value)"
                        >
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="userEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiUserAdd, apiUserEdit, apiUserDetail } from '@/api/user'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { useDictOptions } from '@/hooks/useDictOptions.ts'
import { travelAgencyAll } from '@/api/travel_agency.ts'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑用户表' : '新增用户表'
})

// 表单数据
const formData = reactive({
    id: '',
    user_type: '',
    travel_agency_id: 0,
    avatar: '',
    real_name: '',
    nickname: '',
    account: '',
    mobile: '',
    password: '',
    password_confirm: '',
    sex: 0,
    is_disable: 0,
    is_show: false
})

const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}

// 表单验证
const formRules = reactive<any>({
    user_type: [
        {
            required: true,
            message: '请选择用户类型',
            trigger: ['blur']
        }
    ],
    real_name: [
        {
            required: true,
            message: '请输入真实姓名',
            trigger: ['blur']
        }
    ],
    nickname: [
        {
            required: true,
            message: '请输入用户昵称',
            trigger: ['blur']
        }
    ],
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入用户电话',
            trigger: ['blur']
        }
    ],
    sex: [
        {
            required: true,
            message: '请选择用户性别',
            trigger: ['blur']
        }
    ],
    is_disable: [
        {
            required: true,
            message: '请选择是否禁用',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: ['blur']
        }
    ] as any[],
    password_confirm: [
        {
            required: true,
            message: '请输入确认密码',
            trigger: ['blur']
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ] as any[]
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    formRules.password = []
    formRules.password_confirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const handleUserTypeChange = (val: number) => {
    formData.is_show = val === 2 // 动态控制其他字段的显示
    if(formData.travel_agency_id === 0){
        formData.travel_agency_id = ''
    }
    if(val != 2)
    {
        formData.travel_agency_id = 0
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiUserDetail({
        id: row.id
    })
    setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData }
    mode.value == 'edit' ? await apiUserEdit(data) : await apiUserAdd(data)
    popupRef.value?.close()
    emit('success')
}

const { optionsData } = useDictOptions<{
    trave_agency: any[]
}>({
    trave_agency: {
        api: travelAgencyAll
    }
})

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
